from collections import namedtuple,OrderedDict
from const import *
from string import ascii_letters
from pathlib import Path
import os

def col2num(col):
    num = 0
    for c in col:
        if c in ascii_letters:
            num = num * 26 + (ord(c.upper()) - ord('A')) + 1
    return num

def num2col(n):
    string = ""
    while n > 0:
        n, remainder = divmod(n - 1, 26)
        string = chr(65 + remainder) + string
    return string

def createQueryCondition(values:dict) -> QueryCondition:
    valid = {}
    for k, v in values.items():
        if k in QueryCondition._fields and len(v)!=0:
            if k in ['q_gender','q_education','q_degree','q_item_if']:
                if v in [i[0] for i in [q_gender,q_education,q_degree,q_item_if]] :
                    continue
            col_name_letter= query_column_mapping.get(k)
            # # for pandas, so minus 1
            # col_name_number= [col2num(letters) -1 for letters in col_name_letter]

            valid[k]=QueryLocation(query_column_mapping.get(k),query_column_mapping.get(k),v)
    return QueryCondition(**valid)

def createDir(home_dir,name):
    name_dir=os.path.join(home_dir,name)
    print('Create dir id:',name_dir)
    try:
        Path(name_dir).mkdir(parents=True, exist_ok=True)
    except:
        print(f'Error to create dir:{name}')
    
    for dir in pdf_folder:
        try:
            Path(os.path.join(name_dir,dir)).mkdir(parents=True, exist_ok=True)
        except:
            print(f'Error to create dir:{os.path.join(name_dir,dir)}')

def loopFolder(dir):
    pdfs=OrderedDict()
    no_cet = True
    
    if not os.path.isdir(dir):
        return pdfs,no_cet
    
    # for k,dname in zip(cert_rows,pdf_folder):
    #     pdfs[k] = ([],'')
    #     pdf_fpath = os.path.join(dir,dname)
    #     if os.path.isdir(pdf_fpath):
    #         pdfs[k]= (os.listdir(pdf_fpath),pdf_fpath)
    #         no_cet = False
    i = 1

    for j,pdf in enumerate(os.listdir(dir)):
        no_cet = False
        if i not in pdfs:
            pdfs[i] = ([],dir)
        pdfs[i][0].append(pdf)
        # each row show 3 files
        if (j+1)%3 == 0:
            i +=1
    return pdfs,no_cet

def format_table_data(df_query:[[]])->[[]]:
    table=[]
    for row in df_query:
        r=[]
        for v in row:
            print('xx',str(v))
            if str(v) in ['None','nan','NaT']:
                v= ''
            if str(v).endswith(' 00:00:00'):
                v = str(v).split(' ')[0]
            if str(v).endswith('.0'):
                v = str(v).split('.')[0]
            r.append(v)
        table.append(r)
    return table